/*
 * Copyright 2007 Jeffrey Palm
 */

import java.io.*;
import java.util.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class Bloglines extends MIDlet {

  protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
		
  }

  protected void pauseApp() {

  }
	
  private String username;
  private String password;

  protected void startApp() throws MIDletStateChangeException {
    setCurrent(new UsernameForm(null,this));
  }

  void startShowing() {
    new Thread(new Runnable() {
	public void run() {
	  try {
	    showProgress("Searching","Searching for feeds...");
	    Vector subs = request("listsubs");
	    FeedListList lst = new FeedListList(Bloglines.this);
	    lst.parse(subs);
	    setCurrent(lst);
	  } catch (Exception e) {e.printStackTrace();}
	}}).start();

  }

  protected void showProgress(String str) {
    showProgress(str,str);
  }
  protected void showProgress(String title,String str) {
    Form f = new Form(title);
    f.append(str);
    setCurrent(f);
  }

  private void dump(BufferedReader in) throws IOException {
    String line;
    while ((line = in.readLine()) != null) {
      System.out.println(line);
    }
    in.close();
  }

  protected void setCurrent(Displayable d) {
    Display.getDisplay(this).setCurrent(d);
  }

  public void setUsername(String username) {
    Configuration.Set(Configuration.USERNAME_PARAM, username);
    this.username = username;
  }

  public void setPassword(String password) {
    Configuration.Set(Configuration.PASSWORD_PARAM, password);
    this.password = password;
  }

  public Vector request(String link) throws Exception {
    String userPassword = username + ":" + password;
    String encoding = Base64Coder.encodeString(userPassword);
    String post = "http://rpc.bloglines.com/" + link;
    System.out.println("request: " + post);
    HttpConnection con = (HttpConnection)Connector.open(post);
    con.setRequestProperty ("Authorization", "Basic " + encoding);
    StringBuffer sb = new StringBuffer();
    BufferedReader in = new BufferedReader(new InputStreamReader(con.openInputStream()));
    Vector res = new Vector();
    String line;
    while ((line = in.readLine()) != null) res.addElement(line);
    in.close();
    return res;
  }

}
